package com.yu.boot.admin.web;

import com.yu.boot.admin.model.Category;
import com.yu.boot.admin.model.CategoryCover;
import com.yu.boot.admin.service.CategoryCoverService;
import com.yu.boot.admin.service.CategoryService;
import com.yu.boot.lib.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@RequestMapping("import")
@Controller
@Slf4j
public class ImportController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategoryCoverService categoryCoverService;

    @Autowired
    HttpServletRequest request;

    @RequestMapping("view")
    public String view(String msg, ModelMap map) {
        map.put("msg", msg);
        return "import";
    }

    @RequestMapping("")
    public String imports(@RequestParam(value = "file") MultipartFile file) {
        try {
            String userName = AuthUtil.getUserName(request);
            long size = file.getSize();
            if (size == 0) {
                throw new RuntimeException("文件为空");
            }
            List<String> strings = org.apache.commons.io.IOUtils.readLines(file.getInputStream(), "utf-8");
            StringBuilder sb = new StringBuilder();
            for (String string : strings) {
                sb.append(string);
            }
            SAXReader reader = new SAXReader();
            reader.setEncoding("utf-8");
            byte[] bytes = IOUtils.toByteArray(file.getInputStream());
            String s = new String (bytes, StandardCharsets.UTF_8);
            s = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+s.replaceAll("&","&amp;");
            org.dom4j.Document read = reader.read(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));

            Element rootElement = read.getRootElement();
            List<Element> covers = rootElement.element("body").elements();

            Integer uerId = AuthUtil.getUser(request).getId();

            covers.stream().forEach(element -> {
                Element h3 = element.element("h3");
                String coverName = h3.getText();
                String coverId = h3.attributeValue("data-id");

                List<CategoryCover> categoryCovers = categoryCoverService.listByUserIdCoverName(uerId, coverName);
                if (categoryCovers.isEmpty()) {
                    CategoryCover categoryCover = new CategoryCover();
                    categoryCover.setUserId(uerId)
                            .setCreated(new Date())
                            .setCoverName(coverName);
                    categoryCoverService.add(categoryCover);
                    coverId = String.valueOf(categoryCover.getId());
                } else {
                    coverId = String.valueOf(categoryCovers.get(0).getId());
                }
                List<Element> elements = element.elements("ul");
                for (Element element1 : elements) {
                    Category category = new Category();
                    Element li = element1.element("li");
                    Element a = li.element("a");
                    String href = a.attributeValue("href");
                    String title = a.attributeValue("title");
                    String name = a.getText();
                    category.setCover(coverId).setName(name).setDescription(title)
                            .setParentName(userName).setAncestors(href)
                            .setLevel(false).setCreated(new Date());
                    categoryService.add(category);
                }
            });
        } catch (Exception e) {
            log.error("导入失败", e);
            try {
                return "redirect:import/view?msg=" + URLEncoder.encode(e.getMessage(), "utf-8");
            } catch (UnsupportedEncodingException e1) {
            }
        }
        return "redirect:import/view?msg=success";
    }

}
